//
//  CustomDrawView.m
//  iMagic
//
//  Created by Tang Xiaoping on 6/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CustomDrawView.h"
#import <QuartzCore/QuartzCore.h>
#import <math.h>

@implementation NSMutableArray (Shuffling)

- (void)shuffle
{
	
	static BOOL seeded = NO;
	if(!seeded)
	{
		seeded = YES;
		srandom(time(NULL));
	}
	
    NSUInteger count = [self count];
    for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        int nElements = count - i;
        int n = (random() % nElements) + i;
        [self exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
}

@end

@implementation CustomDrawView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
		imageArray = [[NSMutableArray alloc] init];
		labelArray = [[NSMutableArray alloc] init];
        [self loadImage];
		[self loadLabel];
		[self randomImage];
		
    }
    return self;
}

- (void) loadImage {
	NSError *error;
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
	
	NSArray *dirContents = [fileManager contentsOfDirectoryAtPath: bundleRoot error: &error];
	NSArray *onlyPng = [dirContents filteredArrayUsingPredicate: [NSPredicate predicateWithFormat: @"self ENDSWITH '.png'"]];
	
	for (int i = 0; i < onlyPng.count; i++) {
		NSString *pngName = [onlyPng objectAtIndex: i];
		if ([pngName isEqualToString:@"icon.png"]) {
			continue;
		}
		UIImage *newImg = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] bundlePath], pngName]];
		[imageArray addObject:newImg];
		[newImg release];
	}
}

- (void)loadLabel
{
	for (int i = 0; i < 99; i++) {
		NSString *str = [NSString stringWithFormat:@"%d", i + 1];
		[labelArray addObject:str];
	}
}

- (void)randomImage
{
	[imageArray shuffle];
	[labelArray shuffle];
}

void MyDrawWithShadows (CGContextRef myContext,float wd, float ht)
{
	CGSize myShadowOffset = CGSizeMake(-15, 20);
	float  myColorValues[] = {1, 0, 0, .6};
	CGColorRef myColor;
	CGColorSpaceRef myColorSpace;
	
	CGContextSaveGState(myContext);
	
	CGContextSetShadow(myContext, myShadowOffset, 5);
	
	// Draw a green solid circle
    CGContextSetRGBFillColor(myContext, 0, 255, 0, 1);
    CGContextFillEllipseInRect(myContext, CGRectMake(100, 100, 25, 25));
	
	CGContextSetRGBStrokeColor(myContext, 0, 0, 255, 1);
    CGContextStrokeEllipseInRect(myContext, CGRectMake(200, 200, 50, 50));

	
	CGContextSetRGBFillColor(myContext, 0, 1, 0, 1);
	CGContextFillRect(myContext, CGRectMake(wd/3 + 75, ht/2, wd/4, ht/4));
	
	myColorSpace = CGColorSpaceCreateDeviceRGB();
	myColor = CGColorCreate(myColorSpace, myColorValues);
	
	CGContextSetShadowWithColor(myContext, myShadowOffset, 5, myColor);
	CGContextSetRGBFillColor(myContext, 0, 0, 1, 1);
	CGContextFillRect(myContext, CGRectMake(wd/3 - 75, ht/2-100, wd/4, ht/4));

	
	drawText(myContext, 50, 50, @"hello");
	
	CGColorRelease(myColor);
	CGColorSpaceRelease(myColorSpace);
	
	CGContextRestoreGState(myContext);
}

void drawText(CGContextRef ctx, float x, float y, NSString* text)
{
	const char *str = [text cStringUsingEncoding:NSASCIIStringEncoding];
	CGContextSelectFont(ctx, "Helvetica", 15, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode(ctx, kCGTextFill);
    CGContextSetRGBFillColor(ctx, 0, 0, 0, 1);
	CGAffineTransform xform = CGAffineTransformMake(
													1.0,  0.0,
													0.0, -1.0,
													0.0,  0.0);
    CGContextSetTextMatrix(ctx, xform);
	CGContextShowTextAtPoint(ctx, x, y, str, strlen(str));
}

void drawTexture(CGContextRef ctx, CGRect rect, UIImage* image)
{
//	int width = CGImageGetWidth(image);
//	int height = CGImageGetHeight(image);
//	CGSize size = CGSizeMake(width, height);
//	CGRect imageRect = CGRectMake(0, 0, width, height);
//	UIGraphicsBeginImageContext(size);
//	CGContextSaveGState(ctx);
//	CGContextTranslateCTM(ctx, 0, height); 
//	//CGContextScaleCTM(ctx, 1.0, -1.0); 
//	CGContextDrawImage(ctx, imageRect, image);
//	CGContextRestoreGState(ctx);
//	UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
//	UIGraphicsEndImageContext();
	[image drawInRect:rect];
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
	//10x1+9x2=320         x1 = 5   x2 = 30;
	//12y1+11y2=480-20     y1 = 11  y2 = 30
    // Drawing code
	CGContextRef ctx = UIGraphicsGetCurrentContext();
    //CGContextClearRect(ctx, rect);
	//MyDrawWithShadows(ctx, rect.size.width, rect.size.height);
	
	int randImage = arc4random()%99;
	yourImage = [imageArray objectAtIndex:randImage];
	
	CGSize myShadowOffset = CGSizeMake(10, -15);
	CGContextSetShadow(ctx, myShadowOffset, 5);
	for (int i = 0; i < 11; i++) {
		for (int j = 0; j < 9; j++) {
			//NSLog(@"index = %d", i*9 + j);
			int x = j * 30 + 5  * (j + 1);
			int y = i * 30 + 11 * (i + 1);
			
			UIImage *image;
			
			int index = i * 9 + j;
			
			NSString *str = [labelArray objectAtIndex:index];
			if ([str intValue] % 9 == 0) {
				image = yourImage;
			}
			else {
				image = [imageArray objectAtIndex:index];
			}
			CGRect rect = CGRectMake(x+2, y+2, 30-4, 30-4);
			drawTexture(ctx, rect, image);
			
			drawText(ctx, x+5, y, str);
		}
	}
	
	//draw path
	CGContextBeginPath(ctx);
	CGMutablePathRef thePath = CGPathCreateMutable();
	for (int i = 0; i < 10; i++) {
		CGFloat x = 0;
		CGFloat y = (i + 1) * (11 + 30);
		CGPathMoveToPoint(thePath, NULL, x,   y);
		CGPathAddLineToPoint(thePath, NULL, 320, y);
	}
	for (int i = 0; i < 8; i++) {
		CGFloat x = (i + 1) * (5 + 30) + 2.5;
		CGFloat y = 0;
		CGPathMoveToPoint(thePath, NULL, x, y);
		CGPathAddLineToPoint(thePath, NULL, x, 480);
	}

	CGContextAddPath(ctx, thePath);
	CGContextStrokePath(ctx);
	CGPathRelease(thePath);
	
//	CGMutablePathRef path = CGPathCreateMutable();
//	CGPathMoveToPoint(path, NULL, 0, 0);
//	CGPathAddLineToPoint(path, NULL, self.bounds.size.width, self.bounds.size.height);
//	
//	CGContextRef context = UIGraphicsGetCurrentContext();
//	UIColor *black = [UIColor colorWithRed: 0 green: 0 blue: 0 alpha: 0.5];
//	CGContextSetStrokeColorWithColor(context, black.CGColor);
//	CGContextSetLineWidth(context, 10);
//	CGContextSetLineCap(context, kCGLineCapRound);
//	CGContextAddPath(context, path);
//	CGContextStrokePath(context);
//	CFRelease(path);
	
	
//	int x = 100;
//	for (x=1; x<26; x++) {
//		CGContextSetLineWidth       (ctx, 0.5);
//		CGContextSetRGBStrokeColor  (ctx, 0.0, 0.0, 0.0, 0.25);
//		CGContextMoveToPoint        (ctx, 160, 200);                
//		CGContextAddLineToPoint(ctx, 160 + (160.0 * (cos((x*14.4)*(M_PI/180)))), 200 + (160.0 * (sin((x*14.4)*(M_PI/180)))));              
//		CGContextStrokePath(ctx);                           // Why is this not showing both line color and infill?
//		
//		//CGContextSetFillColorWithColor   (ctx, [UIColor whiteColor].CGColor);       
//		//CGContextFillPath           (ctx);
//	}
	
	//UIImage *image = [UIImage imageNamed:@"123.png"];
	//drawTexture(ctx, CGRectMake(0, 0, 100, 100), image);

}

- (UIImage*)getYourImage
{
	return yourImage;
}

- (void)dealloc
{
	[imageArray removeAllObjects];
	[imageArray release];
	
	[labelArray removeAllObjects];
	[labelArray release];
	
    [super dealloc];
}

@end
